package com.olmarket.core.entity;

import com.olmarket.core.entity.constant.UserType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * spring security 使用
 *
 * @author: qwesde@hust.edu.cn
 * @date: 2021/2/13 14:33
 */

public class SecurityUserDetails implements UserDetails {

    private User user;

    public SecurityUserDetails(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 获取当前用的权限，当前系统一个用户对应一个权限
        String role;
        switch (user.getUserType()) {
            case UserType.ADMIN:
                role = "admin";
                break;
            case UserType.STUDENT:
                role = "student";
                break;
            case UserType.UNKNOWN:
            default:
                role = "unknown";
                break;
        }
        return Stream.of(role).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    public int getUserType() {
        return this.user.getUserType();
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
